package com.skycode5.servlet;

import com.skycode5.bean.NewsBean;
import com.skycode5.dao.NewsDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 1.接受post网址 /newsAdd.jsp
 * 2.接受收到传递过来的新闻参数 新闻标题 新闻内容
 * 3.完成新闻的添加
 * 4.跳转到其他页面
 */
@WebServlet("/newsAdd.jsq")
public class NewsAddservlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setCharacterEncoding("utf-8");
        // 会话中获取管理员名称
        String user = (String) req.getSession().getAttribute("User");// 获取会话
        if (user == null || user.equals("")) {
            resp.sendRedirect("login.jsp");//没登陆 跳转到登陆页面
            return;
        }
        String newsTitle = req.getParameter("NewsTitle");
        String newsContent = req.getParameter("NewsContent");
        NewsBean newsBean = new NewsBean();
        newsBean.setNewsTitle(newsTitle);
        newsBean.setNewsContent(newsContent);
        newsBean.setAdminName(user);
        NewsDao newsDao = new NewsDao();
        int result= newsDao.add(newsBean);
        if (result>0) {
            resp.sendRedirect("news.jsp");
        }else {
            try {
                req.getRequestDispatcher("WEB-INF/error.jsp").forward(req,resp);
            } catch (ServletException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
